package com.yhd.controller;


import com.yhd.entity.dto.UserDto;
import com.yhd.model.ResultPage;
import com.yhd.model.dto.WebResultDto;
import com.yhd.service.UserService;
import com.yhd.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 基础控制器
 **/
@Component
public class WebBaseController {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;


    public static WebResultDto fail(String msg){
        WebResultDto webResultDto = new WebResultDto();
        webResultDto.setMsg(msg);
        webResultDto.setCode(-1);
        return webResultDto;
    }


    public static WebResultDto success(Object o){
        WebResultDto webResultDto = new WebResultDto();
        webResultDto.setMsg("ok");
        webResultDto.setCode(0);
        webResultDto.setData(o);
        if(o instanceof ResultPage){
            webResultDto.setCount(((ResultPage)o).getTotal());
        }
        return webResultDto;
    }

    /**
     * @Deprecated 列表数据封装
     * @param resultPage
     * @return: com.ets.ecard.dto.ResultDto
     * @Author: DengJun
     * @date: 2019/7/15
     */
    public WebResultDto success(ResultPage resultPage){
        WebResultDto webResultDto = new WebResultDto();
        webResultDto.setMsg("ok");
        webResultDto.setCount(resultPage.getTotal());
        webResultDto.setCode(0);
        webResultDto.setData(resultPage.getData());
        return webResultDto;
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    public UserDto getUserInfo(HttpServletRequest request){
        String authToken = request.getHeader("auth-token");
        String authType = request.getHeader("auth-type");
        if (null != authToken && !"".equals(authToken) && null != authType && !"".equals(authType)){
            String userId = (String) redisUtils.get(authType + "-"  + authToken);
            //String userId = "fafc444dcb8c49a3a7ae5c1b4e5a94e7";
            if (null != userId && !"".equals(userId)){
                UserDto user = userService.selectUserById(userId);
                if (null != user){
                    return user;
                }
            }
        }
        return null;
    }
}
